package com.tzy.newbank.advice;

import com.tzy.newbank.utils.*;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestControllerAdvice
public class GobalExceptionHandler {

    //类似的注释符号还有@return,@throws,@param,@exception,@since,@author,@version,@deprecated,@serial
    //上面的注释中@param中标注的e和resp，在下面的代码中被鼠标停靠后会显示注释的内容。

//    @ExceptionHandler(value = {LoginException.class,
//            BusinessException.class,
//            NoPowerException.class,
//            TransferErrorException.class,
//            NoPowerException.class,
//            AccountOverDrawnException.class})
//    public @ResponseBody void handleException(Exception e, HttpServletResponse resp) {
//        handleError(resp, e.getMessage());
//    }

    @ExceptionHandler(value = Exception.class)
    public @ResponseBody void handleException(Exception e, HttpServletResponse resp) {
        if (!(e instanceof LoginException || e instanceof BusinessException
                || e instanceof NoPowerException || e instanceof TransferErrorException
                ||e instanceof AccountOverDrawnException ||e instanceof InvalidDepositException)) {
            Logger.getLogger("未知异常").log(Level.SEVERE, "发生了一个未知异常", e);
        }
        handleError(resp, e.getMessage());
    }

    private void handleError(HttpServletResponse resp, String errorMessage) {
        resp.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = resp.getWriter()) {
            out.println("<html><body>");
            out.println("<h1>Error</h1>");
            out.println("<p>" + errorMessage + "</p>");
            out.println("</body></html>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
